package com.ssm.server.sendgoods.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssm.server.boxes.dao.BoxDao;
import com.ssm.server.boxes.model.Box;
import com.ssm.server.boxes.model.Boxes;
import com.ssm.server.common.JsonData;
import com.ssm.server.consts.CmsConstants;
import com.ssm.server.consts.CodeEnum;
import com.ssm.server.consts.SysParamEnum;
import com.ssm.server.sendgoods.dao.AddressDao;
import com.ssm.server.sendgoods.dao.SendGoodsDao;
import com.ssm.server.sendgoods.model.Address;
import com.ssm.server.sendgoods.model.SendGoods;
import com.ssm.server.sendgoods.service.SendGoodsService;
import com.ssm.server.sysparam.dao.SysParamDao;
import com.ssm.server.sysparam.model.SysParam;
import com.ssm.server.user.dao.PrizeBagDao;
import com.ssm.server.user.model.PrizeBag;
import com.ssm.server.user.model.User;
import com.ssm.server.util.JsonUtil;
import com.ssm.server.util.MD5;
import com.ssm.server.util.RedisUtil;
import com.ssm.server.util.StringUtil;
import com.ssm.server.util.TokenUse;
import com.ssm.server.util.WuliuUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author zhangyibo
 */
@Service
@Transactional
public class SendGoodsServiceImpl implements SendGoodsService {
    private static final Logger LOGGER = Logger.getLogger(User.class);
 
    @Autowired
    private AddressDao addressDao;
    
    @Autowired
    private SendGoodsDao sendGoodsDao;
    @Autowired
    private BoxDao boxDao;  
    
    @Autowired
    private PrizeBagDao prizeBagDao;
    
    @Autowired
    private SysParamDao sysParamDao;
    
    
	@Override
	public JsonData getAddressByUser(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		String token = param.get("token");
		try {
		List<Address> address =addressDao.getAddressByUser(TokenUse.getUserID(token));
			jsonData.setData(address);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData saveAddress(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> map = JsonUtil.JsonToMap(param.get("json").toString());
		
		String name = map.get("name").toString();
		String phone = map.get("phone").toString();
		String address = map.get("address").toString();
		String preciseAssress = map.get("preciseAssress").toString();
		String token = param.get("token");
		try {
			Address addresss = new Address();
			addresss.setName(name);
			addresss.setPhone(phone);
			addresss.setAddress(address);
			addresss.setPreciseAssress(preciseAssress);
			addresss.setUserId(TokenUse.getUserID(token));
			addressDao.saveAddress(addresss);
			jsonData.setData(addresss);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData saveSendGoods(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> map = JsonUtil.JsonToMap(param.get("json").toString());
		String bagId = map.get("bagId").toString();
		String addressId = map.get("addressId").toString();
		String type = map.get("type").toString();// 发货类型 0顺丰速运(五件包邮)  1顺丰到付
		String remarks = map.get("remarks").toString();
		String token = param.get("token");
		
		try {
			
			SendGoods sendGoods = new SendGoods();
			sendGoods.setType(Integer.valueOf(type));
			sendGoods.setBagId(bagId);
			sendGoods.setAddressId(Integer.valueOf(addressId));
			sendGoods.setState(0);
			sendGoods.setRemarks(remarks);
			sendGoods.setUserId(TokenUse.getUserID(token));
			String orderNumberCodes="";
			for(int i=0;StringUtil.isEmpty(orderNumberCodes);i++){
				String codes=MD5.getRandom();
				SendGoods isuser=sendGoodsDao.getSendGoodsByorderNumber(codes);
				if(isuser==null){
					orderNumberCodes=codes;
				}
			}
			sendGoods.setOrderNumber(orderNumberCodes);
			sendGoodsDao.saveSendGoods(sendGoods);
			 String[] bagIds = map.get("bagId").toString().split(",");
			 for(int j=0;j<bagIds.length;j++){
			  prizeBagDao.updatePrizeBagState(Integer.valueOf(bagIds[j]));
				}
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	
	@Override
	public JsonData getSendGoods(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String state = maps.get("state").toString();//状态 0为已申请 1为已发货  2为已完成
		int page = Integer.valueOf(param.get("page"));
		int limit = Integer.valueOf(param.get("limit"));
		
			
		String token = param.get("token");// 商品id
		
		try {
			int countSize = limit;
			int pageCount = (page - 1) * countSize;
		  List <SendGoods>  sendGoods =sendGoodsDao.getSendGoods(TokenUse.getUserID(token),Integer.valueOf(state),countSize,pageCount);
		  for (int i = 0; i < sendGoods.size(); i++) {
			Address address =addressDao.getAddressById( sendGoods.get(i).getAddressId());
			  sendGoods.get(i).setAddress(address);
			  String[] bagId = sendGoods.get(i).getBagId().split(",");
				List<PrizeBag> prizeBag = new ArrayList<PrizeBag>();
			  for(int j=0;j<bagId.length;j++){
				  
				  if(bagId[j] != null && !bagId[j] .equals("")){
				  PrizeBag prizeBags =prizeBagDao.getPrizeBagById(Integer.valueOf(bagId[j]));
					prizeBag.add(prizeBags);
			  sendGoods.get(i).setPrizeBag(prizeBag);
				  }
			  }
			}
		    jsonData.setData(sendGoods);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData updateSendGoodsState(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String id = maps.get("id").toString();
		try {
			sendGoodsDao.updateSendGoodsState(Integer.valueOf(id));
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData updateAddress(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String addressId = maps.get("addressId").toString();
		String name = maps.get("name").toString();
		String phone = maps.get("phone").toString();
		String address = maps.get("address").toString();
		String preciseAssress = maps.get("preciseAssress").toString();
		try {
			Address addresss= new Address();
			addresss.setAddressId(Integer.valueOf(addressId));
			addresss.setName(name);
			addresss.setPhone(phone);
			addresss.setAddress(address);
			addresss.setPreciseAssress(preciseAssress);
			addressDao.updateAddress(addresss);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData deleteAddress(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String addressId = maps.get("addressId").toString();
		try {
			addressDao.deleteAddress(Integer.valueOf(addressId));
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("操作失败", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData updateAddressState(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String addressId = maps.get("addressId").toString();
		String token = param.get("token");
        try {
        	addressDao.updateAddressStateAll(TokenUse.getUserID(token));
        	addressDao.updateAddressState(Integer.valueOf(addressId));
	        jsonData.setCodeEnum(CodeEnum.SUCCESS);
        } catch (Exception e) {
	        jsonData.setCodeEnum(CodeEnum.ERROR);
            e.printStackTrace();
        }
        return jsonData;
	}
//	满几件包邮
	@Override
	public JsonData findSysParamByKey(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		try {
			List<SysParam> list = new ArrayList<SysParam>();
			SysParam sysParam = sysParamDao.findSysParamByKey(SysParamEnum.SYSPACKAGEMAILNUMBER.getName());
			SysParam sysParams = sysParamDao.findSysParamByKey(SysParamEnum.SYSTHEDELIVERYTYPE.getName());
			list.add(sysParam);
			list.add(sysParams);
			jsonData.setData(list);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	
//	到付
	@Override
	public JsonData findSysParamByKeys(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		try {
			SysParam sysParam = sysParamDao.findSysParamByKey(SysParamEnum.SYSTHEDELIVERYTYPE.getName());
			jsonData.setData(sysParam);
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	@Override
	public JsonData getSendState(Map<String, String> param) throws Exception {
		JsonData jsonData = new JsonData();
		Map<String, Object> maps = JsonUtil.JsonToMap(param.get("json").toString());
		String orderNumber = maps.get("orderNumber").toString();
		try {
			SendGoods senGoods=sendGoodsDao.getSendGoodsByorderNumber(orderNumber);
			String res=WuliuUtil.realTimeQuery(CmsConstants.KUAIDIYIBAI_CUSTOMER, CmsConstants.KUAIDIYIBAI_KEY, senGoods.getComNumber(), senGoods.getWaybillNumber());
			JSONObject jsonObject=JSON.parseObject(res);
            JSONObject resultMap=JSON.parseObject(jsonObject.get("result").toString());
            Map<String,Object> map=new HashMap<String,Object>();
            if(resultMap.get("state").equals("200")){
            	if(resultMap.get("message").equals("ok")){
            		 map.put("state", resultMap.get("state"));
                     map.put("data", resultMap.get("data"));
                     jsonData.setData(map);
            	}else{
            		jsonData.setCodeEnum(CodeEnum.FAHUO_QUERY_ERROR);
            	}
            }else{
            	jsonData.setCodeEnum(CodeEnum.FAHUO_QUERY_ERROR);
            }
			jsonData.setCodeEnum(CodeEnum.SUCCESS);
		} catch (Exception e) {
			LOGGER.error("ERROR", e);
			jsonData.setCodeEnum(CodeEnum.ERROR);
		}
		return jsonData;
	}
	
}